<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href = '/'>商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>查看商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        表格内容-->
        <el-card class="box-card" style="margin-top:15px;">
                <!--三个按钮z                -->
                <el-row>
                    <el-col :span="4">
                            <el-button type="primary" @click="add_goods">添加</el-button>
                    </el-col>
                    <el-col :span="12">
                            <el-input
                                placeholder="请输入内容"
                                v-model="param.key"
                                clearable>
                            </el-input>
                    </el-col>

                    <el-col :span="4">
                        <el-button type="info" icon="el-icon-search" @click="search()">搜索</el-button>
                    </el-col>
                </el-row>

            <el-table border
                :data="tableData"
                style="width: 100%; margin-top: 10px">
                <el-table-column
                    prop="goods_name"
                    label="商品名称"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="price"
                    label="价格"
                    width="100">
                </el-table-column>
                <el-table-column
                    prop="count"
                    label="账户限购数量"
                    width="100">
                </el-table-column>
                <el-table-column
                    prop="sellcount"
                    label="目前销量"
                    width="100">
                </el-table-column>

                <el-table-column
                    prop="score"
                    label="用户评分"
                    width="100">
                </el-table-column>

                <el-table-column
                    prop="img"
                    label="图片">
                    <template   slot-scope="scope" >
                        <img :src="scope.row.img"  min-width="70" height="70" />
                    </template>
                </el-table-column>

                <el-table-column
                    prop="is_recommended"
                    label="推荐1/不推荐0"
                    width="120">
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="上架1/下架0"
                    width="100">
                </el-table-column>

                <el-table-column
                    prop="brief"
                    label="简介"
                    width="280">
                </el-table-column>
                <el-table-column
                    label="操作">
                    <template   slot-scope="scope">
                        <el-button type="primary" size="mini" @click="edit_goods(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页功能           -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="this.param.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="this.total">
            </el-pagination>


<!--            ////dialog挂载一个table,实现添加功能-->
            <el-dialog  title="添加表单" :visible.sync="add_dialogVisible" width="30%">
                <!--添加菜品种类-->
                <el-form ref="form" :model="Addform" label-width="80px">
                    <el-form-item label="菜品名称">
                        <el-input v-model="Addform.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item    label="菜品价格">
                        <el-input  type="number" v-model="Addform.price"  min="1.00" max="500.00" step="0.01" ></el-input>
                    </el-form-item>
                    <el-form-item label="限购数量">
                        <el-input  type="number" v-model="Addform.count" min="0" ></el-input>
                    </el-form-item>

                    <el-form-item label="简介">
                        <el-input   v-model="Addform.brief"  ></el-input>
                    </el-form-item>
                    <!--上传图片功能   /-->
                    <el-form-item label="菜品图片">
                        <el-upload class="avatar-uploader showUploader"
                                   list-type="picture-card"
                                   ref="businessLicense"
                                   action
                                   :auto-upload="false"
                                   :on-preview="handlePreview"
                                   :on-remove="handleRemove"
                                   :before-remove="beforeRemove"
                                   :on-change="uploadSectionFile"
                                   enctype="multipart/form-data"
                                   :limit="1">
                            <el-dialog :visible.sync="dialogVisible" title='图片预览'>
                                <img v-if="dialogImageUrl" width="100%" height="20px" :src="dialogImageUrl" class="previewImg" alt="">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-dialog>
                        </el-upload>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="add_dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="judgeaddSave">确 定</el-button>
                </span>
            </el-dialog>

            <!-- ///dialog挂载一个table,实现编辑功能, 需要获取到该行的数据，直接填充过去-->
            <el-dialog  title="编辑表单" :visible.sync="edit_dialogVisible" width="30%">
                <!--添加菜品种类-->
                <el-form  :model="Editform" label-width="80px">
                    <el-form-item label="菜品名称">
                        <el-input v-model="Editform.goods_name"></el-input>
                    </el-form-item>
                    <el-form-item type="number" label="菜品价格" >
                        <el-input v-model="Editform.price" type="number"  min="1.00" max="500.00" step="0.01" ></el-input>
                    </el-form-item>
                    <el-form-item  type="number" label="菜品数量">
                        <el-input v-model="Editform.count" type="number"  min="0"></el-input>
                    </el-form-item>

                    <el-form-item   label="菜品简介">
                        <el-input v-model="Editform.brief"  ></el-input>
                    </el-form-item>



                    <el-form-item  label="是否推荐">
                        <el-switch v-model="Editform.is_recommended" active-color="#13ce66" inactive-color="#ff4949"
                                   active-text="推荐" inactive-text="取消推荐" :active-value="1" :inactive-value="0">
                        </el-switch>
                    </el-form-item>

                    <el-form-item  label="是否上架">
                        <el-switch v-model="Editform.status" active-color="#13ce66" inactive-color="#ff4949"
                                   active-text="启用" inactive-text="禁用" :active-value="1" :inactive-value="0">
                        </el-switch>
                    </el-form-item>

                <!--                    ///上传图片-->
                    <el-form-item label="菜品图片">
                        <el-upload class="avatar-uploader showUploader"
                                   list-type="picture-card"
                                   ref="businessLicense"
                                   action
                                   :auto-upload="false"
                                   :on-preview="handlePreview"
                                   :on-remove="handleRemove"
                                   :before-remove="beforeRemove"
                                   :on-change="uploadSectionFile"
                                   enctype="multipart/form-data"
                                   :limit="1">
                            <el-dialog :visible.sync="dialogVisible" title='图片预览'>
                                <img v-if="dialogImageUrl" width="100%" height="20px" :src="dialogImageUrl" class="previewImg" alt="">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-dialog>
                        </el-upload>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="edit_dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editSave">确 定</el-button>
                </span>
            </el-dialog>


        </el-card>

    </div>
</template>

<script>
export default {
    name: "List",
    data() {
        return {
            param:{
                key:'',
                page:1,
                limit:5,
            },
            //表格数据
            tableData: [],
            // 分页
            currentPage:1,
            total:0,
            add_dialogVisible:false,
            edit_dialogVisible:false,
            Addform:{
                goods_name:"默认菜品名",
                price:10,
                count:100,
                img:"",
                brief:"该商品暂无介绍",
            },
            imgdata:[],
            Editform:{
                id:"",    //// 得到商品信息的id
                goods_name:"",
                price:0,
                count:0,
                img:"",
                brief:"",
                status:0,
                is_recommended:0,
            },
            files: [],
            photo: '',
            photoObj: '',
            ///显示图片
            dialogVisible: false,
            dialogImageUrl:''
        }
    },
    methods: {
        ///编辑功能              读取信息到编辑模块
        edit_goods(info){
            this.edit_dialogVisible = true;
            this.Editform.goods_name = info.goods_name;
            this.Editform.count = info.count;
            this.Editform.price = info.price;
            this.Editform.id = info.id;
            this.Editform.img = info.img;
            this.Editform.brief = info.brief;
            this.Editform.status = info.status;
            this.Editform.is_recommended = info.is_recommended;
        },
        ///编辑功能              更新
        editSave(){
            // thinkphp  save函数，当有主键时，更新，否则为新增
            if(this.Editform.goods_name == ''){
                this.$msg.error("菜品名不能为空");
            }
            else{
              this.Editform.busid = window.sessionStorage.getItem("userid")

              this.$ajax.post(this.$API.http+"/api/Goodslist/save", this.Editform).then(res=> {
                        if(res.data.code == 1){  ///成功
                            this.$msg.success(res.data.msg);
                            this.getList();                //请求成功后更新List的数据
                            this.edit_dialogVisible = false;  //关闭弹窗
                            //请空数据
                            this.Editform.goods_name = '';
                            this.Editform.price= '';
                            this.Editform.count = '';
                            this.Editform.img = '';
                            this.Editform.id = '';
                        }
                        else{///错误
                            this.$msg.error(res.data.msg);
                        }
                    },
                    error => {
                        //请求后更新List的数据
                        window.alert(error);
                    }
                )
            }
        },

        ///图片上传功能
        handleRemove(file, fileList) { //文件列表移除文件时的钩子
            this.fileList.map((item,index)=>{
                if(item.uid==file.uid){
                    this.fileList.splice(index,1)
                }
                this.$message.success("图片删除成功！");
            })
        },
        handlePreview(file) {
            //点击文件列表中已上传的文件时的钩子
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
            // console.log(file);
        },
        beforeRemove(file, fileList){   ///删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        uploadSectionFile(file){
            //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
            const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
            const isJPG = typeArr.indexOf(file.raw.type) !== -1;
            const isLt3M = file.size / 1024 / 1024 < 3;
            if (!isJPG) {
                this.$message.error('只能是图片!');
                this.$refs.upload.clearFiles();
                this.files = null;
                return;
            }
            if (!isLt3M) {
                this.$message.error('上传图片大小不能超过 3MB!');
                this.$refs.upload.clearFiles();
                this.files = null;
                return;
            }
            this.files = file.raw;
            console.log(this.files);
            // FormData 对象
            let formData = new FormData();
            // 文件对象
            formData.append('file', this.files);
            let token = window.sessionStorage.getItem('token');

            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'token':token,
                },
                methods: 'post'
            }
            console.log(formData);
            ///上传图片
            this.$ajax.post(this.$API.http+"/api/Imagecommon/uploadimg",formData, config).then(res=>{
                    if(res.data.code == 1){ ///如果成功，将url值传递给当前前端
                        this.Addform.img = res.data.url;
                        this.Editform.img = res.data.url;
                        console.log(res.data.url);
                    }else{
                        this.$message.error(res.data.msg);
                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
            })
        }
        ,

        judgeaddSave(){
            let numReg = /^[0-9]*$/;
            let numRe = new RegExp(numReg);
            console.log(this.Editform.price);
            if(this.Addform.goods_name == ''){
            // if (!numRe.test(this.Editform.price) || !numRe.test(this.Editform.count)) {
                this.$msg.error("菜品名不能为空");
                // this.Editform.price = this.Editform.count = 0;
            }
            else{
                this.addSave();
            }
        },
        ///增加
        addSave(){  // 增加功能
            ///判断价格和数量是否合法
                console.log(this.Addform);
          this.Addform.busid = window.sessionStorage.getItem("userid")

          this.$ajax.post(this.$API.http+"/api/Goodslist/save", this.Addform).then(res=> {
                        if(res.data.code == 1){
                            this.$msg.success(res.data.msg);
                            this.add_dialogVisible = false;  //关闭弹窗
                            this.Addform.goods_name = '默认菜品名';
                            this.Addform.price= 20;
                            this.Addform.img = '';
                            this.getList();
                        }
                        else{
                            this.$msg.error(res.data.msg);
                        }
                    },
                    error => {
                        //请求后更新List的数据
                        window.alert(error);
                    }
                )
        },
        add_goods(){  ///弹窗显示
            this.add_dialogVisible = true;
        },
        edit(info){

        },
        search(){
            this.getList();
        },

        /// 分页
        handleSizeChange(val){
            this.param.limit = val;
            this.getList();
        },
        handleCurrentChange(val){
            this.param.page = val;
            this.getList();
        },

        getList(){  ////查询功能，当前有哪些
             this.$ajax.get(this.$API.http+"/api/Goodslist/index", {params:this.param}).then(res=> {
                     this.tableData = res.data.data;
                     this.total = res.data.total;
                     console.log(this.tableData);
                 },
                 error => {
                     //请求后更新List的数据
                     window.alert(error);
                 }
             )
        },
        del(id){  ////删除功能
            // console.log(id)
            this.$ajax.get(this.$API.http+"/api/Goodslist/delete", {params:{id:id}}).then(res=> {
                    if(res.data.code == 1){
                        this.$msg.success(res.data.msg);
                        this.getList();
                    }
                    else{
                        this.$msg.error(res.data.msg);
                    }
                },
                error => {
                    //请求后更新List的数据
                    window.alert(error);
                }
            )
        }
    }
    ,
    created() {
        this.getList();
    }
}
</script>

<style scoped>


</style>
